package com.mallbook.controller.servlet.admin;

import com.mallbook.model.exception.EmailExitsException;
import com.mallbook.model.exception.ServiceException;
import com.mallbook.model.pojo.Category;
import com.mallbook.model.pojo.PageBean;
import com.mallbook.model.pojo.User;
import com.mallbook.model.service.GoodsService;
import com.mallbook.model.service.UserService;
import com.mallbook.model.utils.MallDefaultConfig;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-07-02
 */
@WebServlet("/admin/user")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opr = req.getParameter("opr");
        if (opr == null) {
            req.getRequestDispatcher("/WEB-INF/admin/user_list.jsp").forward(req, resp);
            return;
        }
        switch (Objects.requireNonNull(opr)) {
            case "initUser":
                doInitUser(req, resp);
                break;
            case "del":
                doDel(req, resp);
                break;
            case "updateSelect":
                doUpdateSelect(req, resp);
                break;
            case "update":
                doUpdate(req, resp);
                break;
            case "shield":
                doShield(req, resp);
                break;
        }
    }

    /**
     * 查询需要修改的数据展示到弹窗
     *
     * @param req
     * @param resp
     */
    private void doUpdateSelect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String uid = req.getParameter("id");
        PrintWriter writer=resp.getWriter();
        try {
            User user = userService.getUser(Integer.parseInt(uid));
            // 存入json格式数据
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username", user.getUsername());
            jsonObject.put("email", user.getEmail());
            jsonObject.put("regTime", user.getRegTime());
            jsonObject.put("state", user.getState());
            jsonObject.put("integral", user.getIntegral());
            jsonObject.put("img", user.getImg());
            jsonObject.put("id", user.getId());
            writer.print(jsonObject);
            writer.close();
        } catch (ServiceException e) {
            e.printStackTrace();
            writer.print("系统维护中");
            writer.close();
        }
    }

    /**
     * 修改数据
     *
     * @param req
     * @param resp
     */
    private void doUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String uid = req.getParameter("uid");
        String email = req.getParameter("email");
        String times = req.getParameter("times");
        String state = req.getParameter("state");
        String integer = req.getParameter("integer");
        System.out.println("**/*/*/*/");
        System.out.println("uid:"+uid+"email:"+email+"times:"+times+"state:"+state+"integer:"+integer);
        JSONObject json=new JSONObject();
        PrintWriter writer=resp.getWriter();
        if (email.isEmpty()) {
            json.put("msg","邮箱不能为空");
            writer.print(json);
            writer.close();
            return;
        }
        if (times.isEmpty()) {
            json.put("msg","用户注册时间不能为空");
            writer.print(json);
            writer.close();
            return;
        }
        if (state.isEmpty()) {
            json.put("msg","用户状态不能为空");
            writer.print(json);
            writer.close();
            return;
        }
        if (integer.isEmpty()) {
            integer = "0";
        }
        try {
            userService.updateUserForAdmin(email, times, Integer.parseInt(state), Integer.parseInt(integer), Integer.parseInt(uid));
            json.put("msg","ok");
            writer.print(json);
            writer.close();
        } catch (EmailExitsException e) {
            e.printStackTrace();
            json.put("msg","邮箱已存在");
            writer.print(json);
            writer.close();
        } catch (ServiceException e) {
            e.printStackTrace();
            json.put("msg","系统维护中");
            writer.print(json);
            writer.close();
        }

//        resp.sendRedirect("/admin/user?opr=initUser&p=1");
    }

    private void doShield(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        String state = req.getParameter("state");
        try {
            userService.disableUser(Integer.parseInt(id), Integer.parseInt(state));
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        resp.sendRedirect("/admin/user?opr=initUser&p=1");
    }

    private void doDel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        try {
            userService.delUser(Integer.parseInt(id));
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        resp.sendRedirect("/admin/user?opr=initUser&p=1");
    }

    private void doInitUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String p = req.getParameter("p");
        String pSize = req.getParameter("pSize");
        String state = req.getParameter("state");
        String name = req.getParameter("name");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime");
        User user = new User();
        if (state != null && !state.equals("0")) {
            user.setState(Integer.parseInt(state));
        }
        if (name == null || name.isEmpty()) {
            name = null;
        }
        if (startTime == null || startTime.isEmpty()) {
            startTime = null;
        }
        if (endTime == null || endTime.isEmpty()) {
            endTime = null;
        }
        user.setUsername(name);
        user.setStartTime(startTime);
        user.setEndTime(endTime);
        user.setIntegral(null);

        if (pSize != null && !pSize.isEmpty()) {
            MallDefaultConfig.USER_PAGE_SIZE = Integer.parseInt(pSize);
        } else {
            MallDefaultConfig.USER_PAGE_SIZE = 5;
        }

        Integer page = null;
        if (p == null || p.equals("")) {
            page = 1;
        } else {
            page = Integer.parseInt(p);
        }

        try {
            PageBean<User> users = userService.getUsersByCondition(user, page);
            req.setAttribute("pageBean", users);
            req.setAttribute("seachUser", user);
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        req.getRequestDispatcher("/WEB-INF/admin/user_list.jsp").forward(req, resp);
    }
}
